# @File     : 爬取城市编码.py
# @function : #爬取所有城市的编码
# @Software : PyCharm Community Edition
# @Knowledge: BeautifulSoup、写文件

import requests
from bs4 import BeautifulSoup


# 爬取城市编号及城市名称，将数据保存到city.txt文件中
def spider_city_code():
    # 请求的网址
    url = "http://localhost:8080/weather/city_code.html"
    # 保存的文本文件名
    file_name = "city.txt"

    # 补全代码：使用requests库发送请求，使用BeautifulSoup库提取页面中的城市编号和城市名称，将数据写入city.txt文件中
    response = requests.get(url)
    if response.status_code == 200:
        content = BeautifulSoup(response.content.decode('utf-8'), 'html.parser')
        code_tag=content.find_all('td')[0]
        with open(file_name, 'w', encoding='utf-8') as f:
            for i in code_tag.children:
                if i.string is not None:
                    f.write(i.string+'\n')


    else:
        print(f"error code: {response.status_code}")

if __name__ == "__main__":
    spider_city_code()
